package com.molihub.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.molihub.component.MyWebSocketHandler;
import com.molihub.entity.*;
import com.molihub.utils.LogUtils;
import com.molihub.utils.StringUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: LikeController
 * @Description: 用于处理文章点赞的处理器
 * @author: GGBOY
 * @date 2020/2/12 15:08
 * @Version: 1.0
 **/
@Controller
public class LikeController extends BaseController {
    private static Logger logger = LogUtils.getInstance(LikeController.class);

    /**
     * 给文章点赞,并且通知作者有人点赞
     *
     * @param articleId 文章ID
     * @param userName  用户名
     * @return java.lang.String
     * @author GGBOY
     * @date 2020/2/12
     */
    @ResponseBody
    @PostMapping("/like/{userName}/{articleId}")
    public String like(@PathVariable String userName, @PathVariable Integer articleId) {
        // 转换成JSON数据返回
        JSONObject returnJson = new JSONObject();
        // 获取点赞的用户
        User user = userService.getUserByUserName(userName);
        // 查找是否已经存在了点赞记录
        Integer record = articleLikeService.getLikeRecordByUserAndArticleId(user.getUserId(), articleId);
        // 获取文章标题
        Article article = articleService.getArticleById(articleId);
        if (record != null) {
            logger.info("查询到的点赞记录ID为：" + record);
            // 如果存在，则把这条记录删除
            articleLikeService.deleteRecordByUserAndArticleId(user.getUserId(), articleId);
            returnJson.put("flag", "DELETE");
            // 同时删除消息记录
            messageService.deleteMessages(article.getUserId(), 2);
        } else {
            ArticleLike articleLike = ArticleLike.builder().articleId(articleId).userId(user.getUserId()).build();
            articleLikeService.addLikeRecord(articleLike);
            // 查找出这篇文章现在的点赞数
            Integer count = articleService.getLikeCountByArticle(articleId);
            returnJson.put("flag", "OK");
            returnJson.put("count", count);
            // 同时发条消息提示作者，有人点赞
            RequestMessage requestMessage = new RequestMessage();
            // a用户：点赞的用户ID
            requestMessage.setAUserId(user.getUserId());
            // b用户：作者id
            int authorId = articleService.getArticleById(articleId).getUserId();
            User authorUser = userService.getUserById(authorId);
            requestMessage.setBUserId(authorId);
            JSONObject message = new JSONObject();
            message.put("A", user.getUserName());
            message.put("B", authorUser.getUserName());
            message.put("flag", "6");
            message.put("aUserInfo", user);
            message.put("bUserInfo", authorUser);
            if (article.getArticleTitle() == null) {
                // 表明点赞的是状态，那就显示点赞的状态部分内容
                message.put("content", "点赞了你的<h5>" + StringUtils.cutStr(article.getArticleContent(), 20) + "</h5>");
            } else {
                message.put("content", "点赞了你的<h5>" + article.getArticleTitle() + "</h5>");
            }
            requestMessage.setMessageContent(message.toJSONString());
            requestMessage.setIsReceive(0);
            requestMessage.setFlag(6);
            // 向数据库添加一条消息记录
            requestMessageService.addMessage(requestMessage);
            // 封装Message
            Message message1 = Message.builder().messageTime(new Date())
                    .fromUserId(user.getUserId()).toUserId(authorUser.getUserId())
                    .articleId(articleId).articleLikeId(articleLike.getArticleLikeId()).isLooked(0).build();
            messageService.addRecord(message1);
            // 发送消息
            MyWebSocketHandler.aSendMessageToB(user.getUserId(), authorId, message.toJSONString());
        }
        return returnJson.toJSONString();
    }


    @RequestMapping("/refresh/like/{articleId}")
    public String refreshLike(@PathVariable Integer articleId, Model model) {
        // 获取对文章点过赞的用户
        List<User> likeUsers = articleLikeService.findLikeUsersByArticleId(articleId);
        boolean contains = likeUsers.contains(loginUser);
        // 获取文章的评论数
        int commentsSize = articleCommentService.getArticleTotalCommentCount(articleId);
        ArticleToShow articleToShow = ArticleToShow.builder().likeUserList(likeUsers)
                .commentCount(commentsSize).likeCount(likeUsers.size())
                .likeUserList(likeUsers)
                .build();
        logger.info("likeUser size: " + likeUsers.size());
        model.addAttribute("article", articleToShow);
        logger.info("局部刷新点赞页面");
        return "profilePageCommon::like_refresh";
    }
}
